import { baiduParser } from './baiduParser';
import { APIRequester } from './APIRequester';
// @ts-ignore
import { constructRequestParams } from '../../../util/signBuilder';
import {Config} from '../../configuration/config';
//@ts-ignore
import { LanguageCodeAdapter } from '../../../util/LanguageCodeAdapte';


//TODO 添加对不同翻译源的适配
export class APIClient {
  //策略工厂实施
  private parse: Parse | null = null;
  private postObject: Record<string, string> | null = null;
  private readonly config: Config;
  private url: string;

  constructor(Config: Config) {
    this.config = Config;
    this.url = this.config['baidu']['url'];
  }

  private ParserFactory(queryMessage: string, _from: string, _to: string): Parse | null {
    if (this.config['baidu']['enabled'] && this.url.includes('fanyi-api.baidu.com/api/trans')) {
      this.postObject = constructRequestParams(
        this.config['baidu']['app_id'],
        this.config['baidu']['app_key'],
        <string>LanguageCodeAdapter.getCode(_from),
        <string>LanguageCodeAdapter.getCode(_to),
        queryMessage,
        this.config['baidu']['salt']
      );
      return new baiduParser();
    }
    //扩展位
    return null;
  }

  public async fetchData(
    queryMessage: string,
    _from: string,
    _to: string
  ): Promise<string[] | null> {
    //默认使用POST
    this.parse = this.ParserFactory(queryMessage, _from, _to);
    if (this.parse === null) {
      throw new Error('The corresponding API could not be found');
    } else if (this.postObject === null) {
      throw new Error('The postObject is undefined');
    }
    return await new APIRequester(this.parse).fetchData(this.url, this.postObject);
  }
}
